package com.example.backend.controller;

import com.example.backend.dto.*;
import com.example.backend.service.NotificationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 通知管理控制器
 */
@RestController
@RequestMapping("/api/notifications")
@Tag(name = "通知管理", description = "通知的增删改查和统计功能")
@SecurityRequirement(name = "Bearer Authentication")
public class NotificationController {
    
    private final NotificationService notificationService;
    
    public NotificationController(NotificationService notificationService) {
        this.notificationService = notificationService;
    }
    
    @PostMapping
    @Operation(summary = "创建通知", description = "创建新的通知")
    public ResponseEntity<ApiResponse<NotificationDto>> createNotification(@Valid @RequestBody SendNotificationRequest request) {
        try {
            var notification = notificationService.createNotification(request);
            return ResponseEntity.ok(ApiResponse.success("通知创建成功", convertToDto(notification)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("创建通知失败: " + e.getMessage()));
        }
    }
    
    @GetMapping
    @Operation(summary = "获取通知列表", description = "分页获取通知列表，支持多条件过滤")
    public ResponseEntity<ApiResponse<PageResponse<NotificationDto>>> getNotifications(
            NotificationFilter filter,
            Pageable pageable) {
        try {
            Page<NotificationDto> page = notificationService.findByFilter(filter, pageable);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取通知列表失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    @Operation(summary = "获取通知详情", description = "根据ID获取通知详情")
    public ResponseEntity<ApiResponse<NotificationDto>> getNotification(
            @Parameter(description = "通知ID") @PathVariable Long id) {
        try {
            var notification = notificationService.findById(id)
                    .orElseThrow(() -> new RuntimeException("通知不存在"));
            return ResponseEntity.ok(ApiResponse.success(convertToDto(notification)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取通知失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}")
    @Operation(summary = "更新通知", description = "更新通知信息")
    public ResponseEntity<ApiResponse<NotificationDto>> updateNotification(
            @Parameter(description = "通知ID") @PathVariable Long id,
            @Valid @RequestBody UpdateNotificationRequest request) {
        try {
            var notification = notificationService.updateNotification(id, request);
            return ResponseEntity.ok(ApiResponse.success("通知更新成功", convertToDto(notification)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("更新通知失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/read")
    @Operation(summary = "标记为已读", description = "标记通知为已读状态")
    public ResponseEntity<ApiResponse<NotificationDto>> markAsRead(
            @Parameter(description = "通知ID") @PathVariable Long id) {
        try {
            var notification = notificationService.markAsRead(id);
            return ResponseEntity.ok(ApiResponse.success("通知已标记为已读", convertToDto(notification)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("标记通知失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除通知", description = "删除指定的通知")
    public ResponseEntity<ApiResponse<String>> deleteNotification(
            @Parameter(description = "通知ID") @PathVariable Long id) {
        try {
            notificationService.deleteNotification(id);
            return ResponseEntity.ok(ApiResponse.success("通知删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("删除通知失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/batch/read")
    @Operation(summary = "批量标记为已读", description = "批量标记多个通知为已读")
    public ResponseEntity<ApiResponse<BatchResult>> markAsReadBatch(@RequestBody BatchOperationRequest request) {
        try {
            int count = notificationService.markAsReadBatch(request.getIds());
            return ResponseEntity.ok(ApiResponse.success("批量标记成功", BatchResult.of(count, request.getIds().size())));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量标记失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/batch/unread")
    @Operation(summary = "批量标记为未读", description = "批量标记多个通知为未读")
    public ResponseEntity<ApiResponse<BatchResult>> markAsUnreadBatch(@RequestBody BatchOperationRequest request) {
        try {
            int count = notificationService.markAsUnreadBatch(request.getIds());
            return ResponseEntity.ok(ApiResponse.success("批量标记成功", BatchResult.of(count, request.getIds().size())));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量标记失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/batch/delete")
    @Operation(summary = "批量删除", description = "批量删除多个通知")
    public ResponseEntity<ApiResponse<BatchResult>> deleteBatch(@RequestBody BatchOperationRequest request) {
        try {
            int count = notificationService.deleteBatch(request.getIds());
            return ResponseEntity.ok(ApiResponse.success("批量删除成功", BatchResult.of(count, request.getIds().size())));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量删除失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/stats")
    @Operation(summary = "获取通知统计", description = "获取通知的统计信息")
    public ResponseEntity<ApiResponse<NotificationStatsDto>> getNotificationStats(
            @RequestParam Long userId) {
        try {
            var stats = notificationService.getNotificationStats(userId);
            return ResponseEntity.ok(ApiResponse.success(stats));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/unread-count")
    @Operation(summary = "获取未读数量", description = "获取用户的未读通知数量")
    public ResponseEntity<ApiResponse<UnreadCountDto>> getUnreadCount(
            @RequestParam Long userId) {
        try {
            var unreadCount = notificationService.getUnreadCount(userId);
            return ResponseEntity.ok(ApiResponse.success(unreadCount));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取未读数量失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/search")
    @Operation(summary = "搜索通知", description = "根据关键词搜索通知")
    public ResponseEntity<ApiResponse<PageResponse<NotificationDto>>> searchNotifications(
            @RequestParam Long userId,
            @RequestParam(required = false) String keyword,
            Pageable pageable) {
        try {
            Page<NotificationDto> page = notificationService.searchNotifications(userId, keyword, pageable);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("搜索通知失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/unread")
    @Operation(summary = "获取未读通知", description = "获取用户的未读通知列表")
    public ResponseEntity<ApiResponse<List<NotificationDto>>> getUnreadNotifications(
            @RequestParam Long userId) {
        try {
            var notifications = notificationService.getUnreadNotifications(userId);
            return ResponseEntity.ok(ApiResponse.success(notifications));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取未读通知失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/urgent")
    @Operation(summary = "获取紧急通知", description = "获取用户的紧急通知列表")
    public ResponseEntity<ApiResponse<List<NotificationDto>>> getUrgentNotifications(
            @RequestParam Long userId) {
        try {
            var notifications = notificationService.getUrgentNotifications(userId);
            return ResponseEntity.ok(ApiResponse.success(notifications));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取紧急通知失败: " + e.getMessage()));
        }
    }
    
    private NotificationDto convertToDto(com.example.backend.domain.entity.Notification notification) {
        return NotificationDto.builder()
                .id(notification.getId())
                .userId(notification.getUserId())
                .title(notification.getTitle())
                .content(notification.getContent())
                .type(notification.getType())
                .channel(notification.getChannel())
                .status(notification.getStatus())
                .priority(notification.getPriority())
                .actionUrl(notification.getActionUrl())
                .readAt(notification.getReadAt())
                .sentAt(notification.getSentAt())
                .scheduledAt(notification.getScheduledAt())
                .createdAt(notification.getCreatedAt())
                .updatedAt(notification.getUpdatedAt())
                .build();
    }
}
